package com.acane.instagram.feature.video

import android.util.Log
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.pager.VerticalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Divider
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.ModalBottomSheetLayout
import androidx.compose.material.ModalBottomSheetValue
import androidx.compose.material.rememberModalBottomSheetState
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.IconToggleButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.media3.common.MediaItem
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.PlayerView
import coil.compose.AsyncImage
import com.acane.instagram.MainActivity
import com.acane.instagram.R
import com.acane.instagram.core.config.Config
import com.acane.instagram.core.design.theme.InstagramDarkGray
import com.acane.instagram.core.extension.clickableNoRipple
import com.acane.instagram.core.model.PostInfo
import com.acane.instagram.core.model.UserInfo
import com.acane.instagram.core.model.dto.CommentDTO
import com.acane.instagram.core.model.network.datasource.MyRetrofitDatasource
import com.acane.instagram.feature.common.SessionManager
import com.acane.instagram.feature.home.CommentList
import com.acane.instagram.feature.home.HomeViewModel
import com.acane.instagram.feature.notification.NotificationViewModel
import com.acane.instagram.feature.post.PostViewModel
import com.acane.instagram.feature.post.UserCommentBar
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

@Composable
fun VideoRoute (
    toProfile: (String) -> Unit,
){
    VideoScreen(
        toProfile = toProfile
    )
}

// 主界面
@Composable
fun VideoScreen(
    viewModel: VideoViewModel = viewModel(),
    notificationViewModel: NotificationViewModel = viewModel(),
    homeViewModel: HomeViewModel = viewModel(),
    toProfile: (String) -> Unit,
) {
    val recommendVideo = viewModel.recommendVideo.collectAsState()
    val pagerState = rememberPagerState(
        initialPage = 0,
        initialPageOffsetFraction = 0f
    ) {recommendVideo.value.size }
    val isFollowingMap by homeViewModel.isFollowingMap.collectAsState() // 收集 isFollowingMap 的状态

    VerticalPager(
        state = pagerState,
        modifier = Modifier.fillMaxSize()
    ) { page ->
        VideoPlayerPage(
            video = recommendVideo.value[page],
            modifier = Modifier.fillMaxSize(),
            isFollowingMap = isFollowingMap,
            notificationViewModel = notificationViewModel,
            homeViewModel = homeViewModel,
            toProfile = toProfile
        )
    }
}

// 单个视频页面
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun VideoPlayerPage(
    video: PostInfo,
    modifier: Modifier = Modifier,
    isFollowingMap: Map<String, Boolean>, // 新增参数
    notificationViewModel: NotificationViewModel,
    homeViewModel: HomeViewModel,
    postViewModel: PostViewModel = viewModel(),
    toProfile: (String) -> Unit,
) {
    val commentBottomSheetState = rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden)
    val postId by homeViewModel.postId.collectAsState(initial = null) // 监听 postId 的变化

    val context = LocalContext.current as MainActivity
    val exoPlayer = remember(context) {
        ExoPlayer.Builder(context).build().apply {
            setMediaItem(MediaItem.fromUri("${Config.ADDRESS}video/${video.urls.first()}"))
            prepare()
        }
    }
    var isPlaying by remember { mutableStateOf(true) }
    var showHeartAnimation by remember { mutableStateOf(false) }

    val isFollowing = isFollowingMap[video.user.id] ?: false // 使用 isFollowingMap 获取状态
    val (isLiked, setIsLiked) = remember { mutableStateOf(false) }
    var likes by remember { mutableStateOf(video.likeCount) }
    val scope = rememberCoroutineScope()

    // 添加状态变量来跟踪回复的评论
    var replyToComment by remember { mutableStateOf<CommentDTO?>(null) }

    var selectedPostUser by remember { mutableStateOf<UserInfo?>(null) }


    // 初始化点赞状态
    LaunchedEffect(Unit) { // 使用 Unit 确保只执行一次
        scope.launch(Dispatchers.IO) {
            val isLikedResponse = MyRetrofitDatasource.judgeIsLiked(
                video.id,
                SessionManager.currentUser?.id
            ).data == true
            setIsLiked(isLikedResponse)
            Log.d("HomeRoute", "🟢 初始化点赞状态：$isLikedResponse")
        }
    }

    // 初始化关注状态
    LaunchedEffect(Unit) {
        scope.launch(Dispatchers.IO) {
            val isFollowingResponse = MyRetrofitDatasource.judgeIsFollowed(
                video.user.id!!,
                SessionManager.currentUser?.id
            ).data == true
            homeViewModel.setIsFollowing(video.user.id, isFollowingResponse)
            Log.d("VideoRoute", "🟢 初始化关注状态isFollowing：$isFollowing")
            Log.d("VideoRoute", "🟢 初始化关注状态isFollowingResponse：$isFollowingResponse")
        }
    }



    // 使用 LaunchedEffect 来在 Compose 中控制状态栏
    LaunchedEffect(Unit) {
        context.showStatusBar() // 视频页面时隐藏状态栏
    }


    // 评论底部弹窗
    ModalBottomSheetLayout(
        sheetState = commentBottomSheetState,
        sheetShape = RoundedCornerShape(topStart = 10.dp, topEnd = 10.dp),
        sheetContent = {
            val comments by homeViewModel.comments.collectAsState()
            val commentData = comments.filter { it.postId == postId }
            val focusRequester = remember { FocusRequester() }
            Log.d("commentDatum", "${commentData}\npostId:$postId")
            if (commentData.isEmpty()) {
                LazyColumn(
                    modifier = Modifier
                        .fillMaxSize()
                        .weight(1f),
                    horizontalAlignment = Alignment.CenterHorizontally,
                ) {
                    item {
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .wrapContentSize(align = Alignment.TopCenter)

                        ) {
                            Image(
                                painter = painterResource(id = R.drawable.bar_horizontal),
                                contentDescription = "bar",
                            )
                        }
                    }
                    item {
                        Text(
                            text = "还没有评论",
                            modifier = Modifier.padding(16.dp),
                            fontSize = 16.sp,
                            fontWeight = FontWeight.Bold,
                        )
                        Text(
                            text = "发起对话。",
                            fontSize = 12.sp,
                            color = InstagramDarkGray
                        )
                    }
                }
                UserCommentBar(
                    postViewModel = postViewModel,
                    onSendComment = {
                        // 修改后
                        if (postId != null) {
                            val newComment = CommentDTO(
                                id = "",
                                commenterId = SessionManager.currentUser?.id!!,
                                postId = postId!!,
                                content = postViewModel.caption,
                                timestamp = "",
                                likes = 0,
                                parentId = replyToComment?.id ?: "",
                            )
                            homeViewModel.sendComment(newComment)
                        }


                        postId?.let {
                            notificationViewModel.sendMessageNotification(
                                commenterId = SessionManager.currentUser?.id!!,
                                postId = it,
                                content = postViewModel.caption,
                            )
                        }
                        Log.d("HomeRoute", "🟢 发送评论：${postViewModel.caption}")
                        postViewModel.caption = ""
                        replyToComment = null

                    },
                    replyToComment = replyToComment,
                    focusRequester = focusRequester,
                )

            } else {
                LazyColumn(
                    modifier = Modifier
                        .fillMaxWidth()
                        .weight(1f)
                ) {
                    // 添加 Bar
                    item {
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .wrapContentSize(align = Alignment.Center)
                        ) {
                            Image(
                                painter = painterResource(id = R.drawable.bar_horizontal),
                                contentDescription = "bar",
                            )
                        }
                    }
                    // 标题区域
                    item {
                        Row(
                            modifier = Modifier.fillMaxWidth(), // 添加宽度约束
                            horizontalArrangement = Arrangement.Center
                        ) {
                            androidx.compose.material3.Text(
                                text = "评论",
                                fontWeight = FontWeight.Bold,
                                fontSize = 12.sp
                            )
                        }
                    }
                    // 分割线
                    item {
                        Divider(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = 2.dp)
                        )
                    }
                    // 评论区域
                    item {
                        val groupedComments = commentData.groupBy {
                            when {
                                it.parentId.isNullOrEmpty() -> "root"
                                else -> it.parentId
                            }
                        }
                        selectedPostUser?.let {
                            CommentList(
                                comments = groupedComments["root"] ?: emptyList(),
                                groupedComments = groupedComments,
                                onReplyClick = { replyToComment = it },
                                notificationViewModel = notificationViewModel,
                                homeViewModel = homeViewModel,
                                scope = scope,
                                selectedPostUser = it,
                                toProfile = toProfile,
                                commentBottomSheetState = commentBottomSheetState,
                                focusRequester = focusRequester,
                            )
                        }
                    }

                }
                UserCommentBar(
                    postViewModel = postViewModel, // 传递回复的评论
                    onSendComment = {
                        val newComment = postId?.let {
                            CommentDTO(
                                id = "",
                                commenterId = SessionManager.currentUser?.id!!,
                                postId = it,
                                content = postViewModel.caption,
                                timestamp = "",
                                likes = 0,
                                parentId = replyToComment?.id ?: ""
                            )
                        }
                        newComment?.let { homeViewModel.sendComment(it) }

                        postId?.let {
                            notificationViewModel.sendMessageNotification(
                                commenterId = SessionManager.currentUser?.id!!,
                                postId = it,
                                content = postViewModel.caption,
                            )
                        }
                        Log.d("HomeRoute", "🟢 发送评论：${postViewModel.caption}")
                        postViewModel.caption = ""
                        replyToComment = null // 清除回复状态
                    },
                    replyToComment = replyToComment,
                    focusRequester = focusRequester,
                )
            }

        }
    ) {
        Box(
            modifier = modifier
                .fillMaxSize()
                .background(Color.Black) // 添加背景色以便调试
        ) {
            // 视频播放层
            AndroidView(
                factory = { ctx ->
                    PlayerView(ctx).apply {
                        player = exoPlayer
                        useController = false
                    }
                },
                modifier = Modifier
                    .fillMaxSize()
                    .clickable { isPlaying = !isPlaying }
                    .background(Color.Black) // 添加背景色以便调试
                    .pointerInput(Unit) {
                        detectTapGestures(
                            onTap = {
                                // 单击：切换播放/暂停
                                exoPlayer.playWhenReady = !exoPlayer.playWhenReady
                            },
                            onDoubleTap = {
                                showHeartAnimation = true
                                if (!isLiked) { // 只有在未点赞的情况下才允许点赞
                                    val newIsLiked = !isLiked // 先计算新状态
                                    setIsLiked(newIsLiked)    // 立即更新本地状态
                                    if (newIsLiked) {         // 根据新状态执行操作
                                        likes += 1
                                        scope.launch {
                                            MyRetrofitDatasource.likePost(video.id)
                                            notificationViewModel.sendLikeNotification(
                                                SessionManager.currentUser?.id!!,
                                                video.id
                                            )
                                        }
                                    } else {
                                        likes -= 1
                                        scope.launch {
                                            MyRetrofitDatasource.unlikePost(video.id)
                                        }
                                    }
                                } else {
                                    // 如果已经点赞，则不处理双击事件
                                    Log.d("VideoPlayerPage", "已点赞，不允许重复点赞")
                                }
                            }
                        )
                    }
            )
            Column(
                modifier = Modifier
                    .align(Alignment.BottomStart)
                    .padding(start = 16.dp, bottom = 30.dp)
            ) {
                Row(
                    modifier = Modifier.clickableNoRipple {
                        video.user.id?.let { toProfile(it) }
                    }
                ) {
                    AsyncImage(
                        model = "${Config.ADDRESS}avatars/${video.user.avatar}",
                        contentScale = ContentScale.Crop,
                        contentDescription = "用户头像",
                        modifier = Modifier
                            .size(50.dp)
                            .clip(CircleShape),
                        error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
                    )
                    video.user.nickName?.let {
                        Text(
                            text = it,
                            modifier = Modifier
                                .padding(start = 8.dp)
                                .align(Alignment.CenterVertically),
                            color = Color.White
                        )
                    }
                    Spacer(modifier = Modifier.width(10.dp))
                    Box(
                        modifier = Modifier
                            .width(60.dp)
                            .height(30.dp)
                            .border(1.dp, Color.White, RoundedCornerShape(10.dp)) // 给 Box 设置边框
                            .align(Alignment.CenterVertically)
                    ) {
                        if (!isFollowing && video.user.id != SessionManager.currentUser?.id) {
                            Button(
                                colors = ButtonDefaults.buttonColors(
                                    containerColor = Color.Black,
                                    contentColor = Color.White
                                ),
                                modifier = Modifier.fillMaxSize()
                                ,
                                onClick = {
                                    // 发送关注请求
                                    scope.launch(Dispatchers.IO) {
                                        homeViewModel.sendFollowRequest(
                                            video.user.id!!,
                                            SessionManager.currentUser?.id!!
                                        )
                                    }
                                    homeViewModel.setIsFollowing(video.user.id!!, true)
                                },
                                shape = RoundedCornerShape(10.dp),
                                elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp),
                                contentPadding = PaddingValues(0.dp) // 设置内容内边距
                            ) {
                                Text(
                                    text = "关注",
                                    fontSize = 12.sp,
                                )
                            }
                        } else if (isFollowing) {
                            Button(
                                colors = ButtonDefaults.buttonColors(
                                    containerColor = Color.Black,
                                    contentColor = Color.White
                                ),
                                modifier = Modifier.fillMaxSize()
                                ,
                                onClick = {
                                    // 发送关注请求
                                    scope.launch(Dispatchers.IO) {
                                        homeViewModel.sendUnFollowRequest(
                                            video.user.id!!,
                                            SessionManager.currentUser?.id!!
                                        )
                                    }
                                    homeViewModel.setIsFollowing(video.user.id!!, false)
                                },
                                shape = RoundedCornerShape(10.dp),
                                elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp),
                                contentPadding = PaddingValues(0.dp) // 设置内容内边距
                            ) {
                                Text(
                                    text = "已关注",
                                    fontSize = 12.sp,
                                )
                            }
                        }

                    }
                }
                video.content?.let {
                    Text(
                        text = it,
                        modifier = Modifier
                            .padding(start = 8.dp),
                        color = Color.White
                    )
                }

            }

            // 交互层
            Column(
                modifier = Modifier
                    .align(Alignment.BottomEnd)
                    .padding(end = 16.dp, bottom = 50.dp)
            ) {
                // 点赞按钮
                IconToggleButton(
                    checked = isLiked,
                    onCheckedChange = {
                        val newIsLiked = !isLiked // 先计算新状态
                        setIsLiked(newIsLiked)    // 立即更新本地状态
                        if (newIsLiked) {         // 根据新状态执行操作
                            likes += 1
                            scope.launch {
                                MyRetrofitDatasource.likePost(video.id)
                                notificationViewModel.sendLikeNotification(
                                    SessionManager.currentUser?.id!!,
                                    video.id
                                )
                            }
                        } else {
                            likes -= 1
                            scope.launch {
                                MyRetrofitDatasource.unlikePost(video.id)
                            }
                        }
                    },
                ) {
                    Icon(
                        painter = painterResource(
                            if (isLiked) R.drawable.heart_filled else R.drawable.heart
                        ),
                        contentDescription = null,
                        modifier = Modifier
                            .size(30.dp)
                            .animateContentSize(),
                        tint = if (isLiked) Color.Red else Color.White
                    )
                }

                Text(
                    text = abbreviateNumber(likes),
                    color = Color.White,
                    modifier = Modifier.align(Alignment.CenterHorizontally)
                )

                Spacer(modifier = Modifier.height(12.dp))

                // 评论按钮
                IconButton(onClick = {
                    scope.launch {
                        homeViewModel.updatePostId(video.id)
                        homeViewModel.loadComments(video.id)
                        selectedPostUser = video.user
                        commentBottomSheetState.show()
                    }
                }
                ) {
                    Icon(
                        painter = painterResource(R.drawable.comment),
                        contentDescription = null,
                        modifier = Modifier.size(30.dp),
                        tint = Color.White
                    )
                }
                Text(
                    text = abbreviateNumber(video.commentCount),
                    color = Color.White,
                    modifier = Modifier.align(Alignment.CenterHorizontally)
                )

                Spacer(modifier = Modifier.height(12.dp))

                // 分享按钮
                IconButton(onClick = { /* 打开分享 */ }) {
                    Icon(
                        painter = painterResource(R.drawable.plus_circle),
                        contentDescription = null,
                        modifier = Modifier.size(30.dp),
                        tint = Color.White
                    )
                }

                Text(
                    text = abbreviateNumber(likes),
                    color = Color.White,
                    modifier = Modifier.align(Alignment.CenterHorizontally)
                )
                Spacer(modifier = Modifier.height(12.dp))
                // 选项按钮
                IconButton(onClick = { /* 打开评论 */ }) {
                    Icon(
                        painter = painterResource(R.drawable.options_verticle_white),
                        contentDescription = null,
                        modifier = Modifier.size(30.dp),
                        tint = Color.White
                    )
                }
            }

            // 双击点赞动画
            if (showHeartAnimation) {
                HeartAnimation{ showHeartAnimation = false }
            }
        }
    }



    LaunchedEffect(isPlaying) {
        if (isPlaying) exoPlayer.play() else exoPlayer.pause()
    }

    DisposableEffect(Unit) {
        onDispose {
            exoPlayer.release()
        }
    }
}

// 心形动画组件
@Composable
fun HeartAnimation(onEnd: () -> Unit) {
    var scale by remember { mutableStateOf(1f) }
    var alpha by remember { mutableStateOf(1f) }

    LaunchedEffect(Unit) {
        scale = 0f
        alpha = 1f
        delay(100) // 增加延迟时间
        scale = 3f
        delay(500) // 增加动画持续时间
        alpha = 0f
        delay(500) // 增加动画持续时间
        onEnd()
    }

    Icon(
        painter = painterResource(R.drawable.heart_filled),
        contentDescription = null,
        tint = Color.White.copy(alpha = alpha),
        modifier = Modifier
            .size(120.dp)
            .graphicsLayer {
                scaleX = scale
                scaleY = scale
            }
    )
}
// 数字缩写扩展
fun abbreviateNumber(number: Int): String {
    // 实现数字缩写逻辑（千、百万等）
    return number.toString()
}
